package java_DesignPattern.CreatorPattern.SingletonPattern.lazy.method1;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 测试单例设计模式-懒汉式:方式1(非线程安全)---->加入synchronized关键字即可解决
 * 100个线程并发调用getInstanceUnSafe()方法,验证是否会创建多个实例(AI生成)
 */
public class TestUnSafe {
    public static void main(String[] args) {
        Set<SingletonUnSafe> set = Collections.synchronizedSet(new HashSet<>());
        ExecutorService executor = Executors.newFixedThreadPool(100);
        AtomicInteger threadCounter = new AtomicInteger(0);

        List<CompletableFuture<Void>> futures = IntStream.range(0, 100)
                .mapToObj(i -> CompletableFuture.runAsync(() -> {
                    int threadId = threadCounter.incrementAndGet();
                    SingletonUnSafe instance = SingletonUnSafe.getInstanceUnSafe();

                    synchronized(set) {
                        if(set.contains(instance)) {
                            System.out.printf("线程 %d 发现冲突实例 (哈希码: %d)%n",
                                    threadId, System.identityHashCode(instance));
                        }
                        set.add(instance);
                    }

                    System.out.printf("线程 %d 获取实例完成 (哈希码: %d)%n",
                            threadId, System.identityHashCode(instance));
                }, executor))
                .collect(Collectors.toList());

        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        executor.shutdown();

        System.out.println("总冲突次数: " + (set.size() < 100 ? 100 - set.size() : 0));

    }
}
